package com.findmeastore.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.findmeastore.bo.UserBo;
import com.findmeastore.bo.UserCredentialsBo;
import com.findmeastore.dao.IUserDAO;

public class UserDAOImpl implements IUserDAO{
	private HibernateTemplate hibernateTemplate;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public boolean findIfUserPresent(String username, String password){
		Criteria crit = hibernateTemplate.getSessionFactory().getCurrentSession().createCriteria(UserCredentialsBo.class);
		crit.add(Restrictions.eq("password", password));
		crit.createAlias("userBo", "user");
		crit.add(Restrictions.eq("user.userName",username));
		List result = crit.list();
		if(result!=null&&result.size()>0){
			return true;
		}
		return false;
	}
	
	public List<UserBo> getAllUsers() {
		return hibernateTemplate.find("from UserBo");
	}
	
	public UserBo getUserById(Integer id){
		return (UserBo)hibernateTemplate.get(UserBo.class, id);
	}
	
	
	public void saveUser(UserBo userBo){
		hibernateTemplate.saveOrUpdate(userBo);
	}

	public UserCredentialsBo getUserCredentialsByUserId(Integer id){
		Criteria crit = hibernateTemplate.getSessionFactory().getCurrentSession().createCriteria(UserCredentialsBo.class);
		crit.add(Restrictions.eq("userId", id));
		List result = crit.list();
		if(result!=null&& result.size()>0){
			return (UserCredentialsBo)result.get(0);
		}
		return null;
	}
	
	public void saveUserCredentials(UserCredentialsBo userCredentialsBo){
		hibernateTemplate.saveOrUpdate(userCredentialsBo);
	}
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
}
